<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  props: {
    options: {
      type: Object,
      required: true,
    },
  },
  setup(props) {
    const chartRef = ref<HTMLElement | null>(null);
    let chart: echarts.ECharts | null = null;

    const resizeHandler = () => {
      if (chart) {
        chart.resize();
      }
    };

    onMounted(() => {
      chart = echarts.init(chartRef.value);
      chart.setOption(props.options);

      window.addEventListener('resize', resizeHandler);
    });

    watch(
      [() => props.options],
      () => {
        chart.setOption(props.options);
      },
      {
        deep: true,
      }
    );

    onUnmounted(() => {
      if (chart) {
        chart.dispose();
        chart = null;
      }

      window.removeEventListener('resize', resizeHandler);
    });

    return {
      chartRef,
    };
  },
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px; /* 根据需要设置图表容器的高度 */
}
</style>